const express = require('express');
const router = express.Router();
const projectController = require('../controllers/projectController');
const versionsController = require('../controllers/versionsController');
const { auth, authorize } = require('../middleware/auth');
const { auditLogger, saveBefore } = require('../middleware/audit');
const { paginate } = require('../middleware/pagination');
const validate = require('../middleware/validate');
const projectValidators = require('../validators/project');
const { Project } = require('../models');

// 应用认证中间件到所有路由
router.use(auth);

// 获取项目列表
router.get('/', 
  paginate,
  projectController.getProjects
);

// 获取项目统计
router.get('/stats', 
  authorize('admin', 'editor'),
  projectController.getProjectStats
);

// 获取项目详情
router.get('/:id', 
  projectController.getProject
);

// 获取项目完整配置
router.get('/:id/config', 
  projectController.getProjectConfig
);

// 创建项目
router.post('/', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(projectValidators.createProject),
  auditLogger('create', 'project'),
  projectController.createProject
);

// 更新项目
router.put('/:id', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(projectValidators.updateProject),
  saveBefore(Project),
  auditLogger('update', 'project'),
  projectController.updateProject
);

// 删除项目
router.delete('/:id', 
  authorize('admin', 'project_admin', 'project_user'),
  saveBefore(Project),
  auditLogger('delete', 'project'),
  projectController.deleteProject
);

// 前置页：获取
router.get('/:id/front-matter',
  authorize('admin', 'project_admin', 'project_user'),
  projectController.getProjectFrontMatter
);

// 前置页：更新
router.put('/:id/front-matter',
  authorize('admin', 'project_admin', 'project_user'),
  auditLogger('update', 'project_front_matter'),
  projectController.updateProjectFrontMatter
);

// 版本：列表
router.get('/:id/versions', authorize('admin','project_admin','project_user'), versionsController.list);
// 版本：发布
router.post('/:id/versions', authorize('admin','project_admin','project_user'), versionsController.publish);
// 版本：获取
router.get('/:id/versions/:versionId', authorize('admin','project_admin','project_user'), versionsController.getOne);
// 版本：对比（轻量）
router.post('/:id/versions/compare', authorize('admin','project_admin','project_user'), versionsController.compare);

module.exports = router;